//
//  NextListsController.m
//  DA_V
//
//  Created by 中亿世联前台 on 15/5/7.
//  Copyright (c) 2015年 zhouhai. All rights reserved.
//

#import "NextListsController.h"
#import "DZNSegmentedControl.h"
#import "AccountTableViewCell.h"
#import "InterFace.h"
#import "UIViewAdditions.h"
#import "DetailsWebViewController.h"
#import "NewLineListCell.h"
#import "DataImageViewController.h"
#import "PMCalendarController.h"
#import "MainTabBarController.h"
#import "ListViewController.h"
#import "LineView.h"
#import "NewLineListCell.h"
#import "ListView.h"
#import "NoPaymentCell.h"
#import "DateBut.h"
#import "PMPeriod.h"
#import "NSDate+Helpers.h"
#import "NextZiDongChanShengListView.h"
#import "NestTableViewCell.h"
#import "MyListModel.h"
#import "PMCalendar.h"

#import "GMDCircleLoader.h"

#import "AlertView.h"
#import "AccountViewController.h"

#import "SDRefresh.h"

#import "Reachability.h"
#import "NetStatus.h"
@interface NextListsController ()<UITextFieldDelegate,PMCalendarControllerDelegate,UITableViewDataSource,UITableViewDelegate,PMCalendarControllerDelegate,UITextViewDelegate,MyListModelDelegate>
{

    
    UIButton *_dateBut;
    UITextField *_searchView;//搜索框
    UITapGestureRecognizer *_singleTap;
}

@property (nonatomic, strong) SDRefreshFooterView *refreshFooter;
@property(nonatomic, strong) DateBut *mydateBtn;//时间but
@property(nonatomic, strong) NSString *mydateNow;//当前时间字符串
@property(nonatomic, strong) PMCalendarController *pmCC;//当前时间字符串
@property(nonatomic, strong) NSMutableArray *xiaXianArray;
@property(nonatomic, strong) MyListModel *myListModel;

@property (nonatomic, copy) NSString *startTime;//开始时间
@property (nonatomic, copy) NSString *endTime;//结束时间
@end

@implementation NextListsController

- (void)dealloc{
    [self.view removeGestureRecognizer:_singleTap];
    [self.refreshFooter removeFromSuperview];
}
- (instancetype)init{

    self = [super init];
    if (self) {
        self.xiaXianArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setHidesBackButton:YES];
    

  
    
    [self createDateButton];
    [self createNavSubviews];
    [self createTableView];
    
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
    _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [self.view addGestureRecognizer:_singleTap];
    
    [self setupFooter];
    
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //获取下线订单数据
    self.myListModel = [[MyListModel alloc] init];
    self.myListModel.myListModelDelegate = self;
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameterDic = @{@"AgentID":agentId};
    
    [self.myListModel getUserList:self.xiaXianArray parameter:parameterDic interface:XiaXianListInterface];

}

- (void)setupFooter
{
    self.refreshFooter = [SDRefreshFooterView refreshView];
    [self.refreshFooter addToScrollView:self.tableView];
    [self.refreshFooter addTarget:self refreshAction:@selector(footerRefreshs)];
}



- (void)footerRefreshs
{
    if (self.xiaXianArray.count % 10 != 0) {
        [self.refreshFooter endRefreshing];
        return;
    }
    NSInteger page = self.xiaXianArray.count / 10;
    page += 1;
    NSString *pageNum = [NSString stringWithFormat:@"%ld",page];
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
     NSDictionary *parameterDic = @{@"AgentID":agentId,@"PageID":pageNum};
    [self.myListModel getaddUserList:self.xiaXianArray parameter:parameterDic interface:XiaXianListInterface];
}

#pragma -mark 点击self.view的点击手势
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    
    //    [self.view endEditing:YES];
    [_searchView resignFirstResponder];
}

#pragma -mark 创建日期Button方法
- (void)createDateButton{
    
    self.mydateBtn = [DateBut dateButWithButton];
    [self.mydateBtn addTarget:self action:@selector(dateBtnActionclick:) forControlEvents:UIControlEventTouchUpInside];
    
    //    UIBarButtonItem *dateButItem = [[UIBarButtonItem alloc] initWithCustomView:self.mydateBtn2];
    //    self.navigationItem.rightBarButtonItem = dateButItem;
    
    UIWindow *windows = [[[UIApplication sharedApplication] delegate ] window];
    self.mydateBtn.frame = CGRectMake(SCREEN_WIDTH-70, 30, 60, 25);
    [windows addSubview:self.mydateBtn];
    
}
#pragma -mark 获取日期
- (void)dateBtnActionclick:(UIButton *)sender{
    NSLog(@"日期");
    self.pmCC = [[PMCalendarController alloc] init];
    self.pmCC.delegate = self;
    self.pmCC.mondayFirstDayOfWeek = YES;
    
    [self.pmCC presentCalendarFromView:sender permittedArrowDirections:PMCalendarArrowDirectionAny animated:YES];
    
    [self calendarController:self.pmCC didChangePeriod:self.pmCC.period];
    
}

static int i = 0;
- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    NSString *time =[NSString stringWithFormat:@"%@"
                     , [newPeriod.startDate dateStringWithFormat:@"yyyy-MM"]];
    [self.mydateBtn setTitle:time forState:UIControlStateNormal];
    
    self.startTime = [NSString stringWithFormat:@"%@%@", [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-"],@"1"];
    NSInteger mydate = [self gainMonthNumber];
    self.endTime = [NSString stringWithFormat:@"%@%zi", [newPeriod.startDate dateStringWithFormat:@"yyyy-MM-"],mydate];
    NSLog(@"开始时间 ＝＝＝ %@,结束时间 ＝＝ %@",_startTime,_endTime);
    
    if (i%2!=0) {
        [self.pmCC dismissCalendarAnimated:YES];
        
    }
    
    i++;
}

#pragma -mark 获取当月天数
-(NSInteger)gainMonthNumber{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //    NSDate *date = [dateFormatter dateFromString:@"2015-02-04 16:01:03"];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    
    NSUInteger numberOfDaysInMonth = range.length;
    return  numberOfDaysInMonth;
}



- (BOOL)calendarControllerShouldDismissCalendar:(PMCalendarController *)calendarController{
    
    
    return YES;
}

- (void)calendarControllerDidDismissCalendar:(PMCalendarController *)calendarController{
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
    
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //选择日期结束
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameterDic = @{@"AgentID":agentId,@"StartTime":self.startTime,@"EndTime":self.endTime};
    
    [self.myListModel getUserList:self.xiaXianArray parameter:parameterDic interface:XiaXianListInterface];
    
}
#pragma -mark 创建TabView

- (void)createTableView{
    UIView *aview = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 40)];
    aview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:aview];
    
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(10, 16, 10, 10)];
    image.image = [UIImage imageNamed:@"自动补货订单---订单详情_03"];
    [aview addSubview:image];
    
    //库存订单View
    UILabel *kuCunTitle = [[UILabel alloc] initWithFrame:CGRectMake(image.right+5, 5, 80, 30)];
    kuCunTitle.text = @"下线订单";
    [aview addSubview:kuCunTitle];
    
    UILabel*line = [[UILabel alloc] initWithFrame:CGRectMake(0, aview.bottom+1, SCREEN_WIDTH, 0.5)];
    line.backgroundColor = DaoHangColor;
    [self.view addSubview:line];
    
    UILabel*lineview = [[UILabel alloc] initWithFrame:CGRectMake(0, line.bottom, SCREEN_WIDTH, 10)];
    lineview.backgroundColor = LineColor;
    [self.view addSubview:lineview];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, lineview.bottom, SCREEN_WIDTH, SCREEN_HEIGHT-aview.frame.size.height-10-1.5-100)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    //返回选购
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-40, SCREEN_WIDTH, 40)];
    backButton.layer.borderColor = BackColor.CGColor;
    backButton.layer.borderWidth = 1.0;
    [backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
//    [backButton setBackgroundImage:[UIImage imageNamed:@"bangdingyinhangka-fanhui"] forState:UIControlStateNormal];
    backButton.backgroundColor = LineColor;
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view  addSubview:backButton];
    
}


#pragma mark -点击日期
- (void)dateBtnAction:(UIButton *)btn
{
//    NSLog(@"日期");
//    self.pmCC = [[PMCalendarController alloc] init];
//    self.pmCC.delegate = self;
//    self.pmCC.mondayFirstDayOfWeek = YES;
//    
//    [self.pmCC presentCalendarFromView:btn
//         permittedArrowDirections:PMCalendarArrowDirectionAny
//                         animated:YES];
//    [self calendarController:self.pmCC didChangePeriod:self.pmCC.period];
    
}




- (void)createNavSubviews{
    
    UIView *qview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    
    UIButton *backBut = [UIButton buttonWithType:UIButtonTypeCustom];
        backBut.frame = CGRectMake(-25, -2, 85, 44);
    
    [backBut setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backBut addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [qview addSubview:backBut];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-110, 5, 200, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:17];
    title.text = @"订单";
    title.textColor = [UIColor whiteColor];
    [qview addSubview:title];
    self.navigationItem.titleView = qview;
    
    //搜索框
    _searchView = [[UITextField alloc]initWithFrame:CGRectMake(backBut.right, 5, SCREEN_WIDTH-backBut.frame.size.width*2, 30)];
    _searchView.layer.masksToBounds = YES;
    
    _searchView.layer.cornerRadius = 6/2;
    _searchView.textColor = [UIColor whiteColor];
    _searchView.backgroundColor = SearColor;
    _searchView.placeholder = @"输入订单号";
    [_searchView setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    _searchView.font = [UIFont fontWithName:nil size:12];
    [qview addSubview:_searchView];
    
    //搜索图片
    
    UIButton *searchImage = [[UIButton alloc]initWithFrame:CGRectMake(_searchView.right-30, 5, 30, 30)];
    searchImage.backgroundColor = [UIColor clearColor];
    [searchImage setBackgroundImage:[UIImage imageNamed:@"订单--我的订单_03_02"] forState:UIControlStateNormal];
    [searchImage addTarget:self action:@selector(searceClick:) forControlEvents:UIControlEventTouchUpInside];
    [qview addSubview:searchImage];
    
    

    
    
}

#pragma -mark 搜索事件
-(void)searceClick:(UIButton *)sender{
  [_searchView resignFirstResponder];

    if ([_searchView.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入要搜索的订单号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //判断是否有网
    NetStatus *status = [[NetStatus alloc] init];
    if ([status.networkStatus isEqualToString:@"无网络"]) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"无网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    NSString *agentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"];
    NSDictionary *parameterDic = @{@"AgentID":agentId,@"MasterOrderID":_searchView.text};
    [GMDCircleLoader setOnView:self.view withTitle:@"加载中···" animated:YES];
    [self.myListModel getUserList:self.xiaXianArray parameter:parameterDic interface:XiaXianListInterface];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];

    if ([_searchView.text isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入要搜索的订单号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return YES;
    }
    return YES;
}


#pragma -mark //获取下线订单数据结束
- (void)getUserlistEnd{
    [self.refreshFooter endRefreshing];
    [GMDCircleLoader hideFromView:self.view animated:YES];
    NSLog(@"下线订单数据＝＝＝＝＝＝＝＝ %@", self.xiaXianArray);
    [self.tableView reloadData];
}

#pragma -mark 向服务器请求返还的网络异常时喝错误时
- (void)requestError{
    [self.refreshFooter endRefreshing];
    [GMDCircleLoader hideFromView:self.view animated:YES];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"网络异常,无法加载数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    
}
- (void)getrequesterror:(NSString *)error{
    [self.refreshFooter endRefreshing];
      [self.tableView reloadData];
    [GMDCircleLoader hideFromView:self.view animated:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:error delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    
}
#pragma -mark 返回按钮事件
- (void)backClick{
    [self.mydateBtn removeFromSuperview];
    self.listVC.hidesBottomBarWhenPushed = NO;
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma -mark textField 的代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.keyboardType = UIKeyboardTypeNumberPad;
    return YES;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.xiaXianArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 270;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = self.xiaXianArray[indexPath.row];
    NSArray *modelarray =dic[@"ProductInfoModelArr"];

    static NSString *accountCell = @"Cell";
    NestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:accountCell];
    if (cell == nil) {
        cell = [[NestTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:accountCell];
    }
    MyListModel *listModel = dic[@"YiFuKuanModel"];
  
    [cell showMyCellView:listModel arr:modelarray];
    if ([listModel.IsMakeup isEqualToString:@"1"]) {
        [cell.zidongChanShengListView.ziDongChanShengListBut setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    }else{
        [cell.zidongChanShengListView.ziDongChanShengListBut setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    return cell;

}

@end
